﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Buddy.Samples
{
    static partial class Program
    {
        static Lid<Data7> sharedResource = new Lid<Data7>(new Data7 { HappenedAt = DateTime.Now, Hits = 0 });

        static void Samples_Lid()
        {
            var tasks = new List<Task>();

            for (var i = 0; i < 10000; i++) { tasks.Add(new Task(ProcessSharedResource)); }
            foreach (var t in tasks) t.Start();

            Task.WaitAll(tasks.ToArray());

            using (var defer = new Defer())
            {
                sharedResource.Lock();
                defer.Also += () => sharedResource.Unlock();

                Console.WriteLine("{0} hits until {1}", sharedResource.Res.Hits, sharedResource.Res.HappenedAt);
            }

            Console.WriteLine("press any key to continue ...");
            Console.ReadKey();
        }

        static void ProcessSharedResource()
        {
            using (var defer = new Defer())
            {
                sharedResource.Lock();
                defer.Also += () => sharedResource.Unlock();

                sharedResource.Res.HappenedAt = DateTime.Now;
                sharedResource.Res.Hits++;
            }
        }
    }

    class Data7
    {
        public DateTime HappenedAt { get; set; }
        public int Hits { get; set; }
    }
}